// store/modules/commonUser.js
import { get, post, put, del } from '@/http/http';

const commonUserModule = {
  namespaced: true,
  state: {
    userInfo: null, // 当前登录用户信息
    userList: [],   // 用户列表
    pagination: {  // 分页参数
      page: 1,
      size: 10,
      total: 0,
      search: {
        username: '',
        realName: ''
      }
    },
    currentDialogType: 'add' // 当前对话框类型
  },
  mutations: {
    // 设置用户信息
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo;
      localStorage.setItem('user', JSON.stringify(userInfo));
    },
    // 设置用户列表
    SET_USER_LIST(state, { list, total }) {
      state.userList = list;
      state.pagination.total = total;
    },
    // 更新分页参数
    SET_PAGINATION(state, pagination) {
      state.pagination = { ...state.pagination, ...pagination };
    },
    // 设置当前对话框类型
    SET_CURRENT_DIALOG_TYPE(state, type) {
      state.currentDialogType = type;
    }
  },
  actions: {
    // 获取用户列表（带分页和搜索）
    async fetchUserList({ commit, state }) {
      try {
        const res = await get('/hqy/users', 
          {
            page: state.pagination.page,
            size: state.pagination.size,
            username: state.pagination.search.username,
            realName: state.pagination.search.realName
          }
        );
        console.log('res',res);
        
        commit('SET_USER_LIST', {
          list: res.data.list,
          total: res.data.total
        });
      } catch (error) {
        let errorMsg = '获取列表失败';
        
        if (error.response) {
          // 服务器有响应但状态码非2xx
          errorMsg = error.response.data.message || 
                     `服务器错误 [${error.response.status}]`;
        } else if (error.request) {
          // 请求已发出但无响应
          errorMsg = '网络连接异常，请检查网络状态';
        } else {
          // 其他错误
          errorMsg = error.message;
        }
        
        console.error('请求错误:', errorMsg);
        throw new Error(errorMsg);
      }
    },


    // 添加用户
    async addUser(_, user) {
      try {
        const res = await post('/hqy/users', user);
        return res;
      } catch (error) {
        const errMsg = error.response?.data?.message || '添加失败';
        console.error('添加异常:', errMsg);
        return Promise.reject(errMsg);
      }
    },

    // 更新用户信息
    async updateUser({ commit }, { id, data }) {
      try {
        const res = await put(`/hqy/users/${id}`, data);
        console.log('up', res);
        commit('SET_USER_INFO', res);
        return Promise.resolve();
      } catch (error) {
        const errMsg = error.response?.data?.message || '更新失败';
        console.error('更新异常:', errMsg);
        return Promise.reject(errMsg);
      }
    },

    // 删除用户
    async deleteUser(_, id) {
      try {
        await del(`/hqy/users/${id}`);
        return Promise.resolve();
      } catch (error) {
        const errMsg = error.response?.data?.message || '删除失败';
        console.error('删除异常:', errMsg);
        return Promise.reject(errMsg);
      }
    }
  }
};

export default commonUserModule;